package com.hansen.library.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;

import com.hansen.library.utils.LogUtils;

/**
 * 延迟加载fragment
 *
 * Created by han on 2019/3/21 0021.
 */

public abstract class BaseLazyFragment extends BaseFragment {

    //Fragment的View加载完毕的标记
    protected boolean isViewCreated;

    //Fragment对用户可见的标记
    protected boolean isUIVisible;

    //是否已经加载过数据，防止重复加载
    protected boolean isLoad;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewCreated = true;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        lazyLoad();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //isVisibleToUser这个boolean值表示:该Fragment的UI 用户是否可见
        if (isVisibleToUser) {
            isUIVisible = true;
            onVisible();
            lazyLoad();
        } else {
            isUIVisible = false;
            onInvisible();
        }

        LogUtils.d("isVisibleToUser===" + isVisibleToUser);
    }


    private void lazyLoad() {
        //这里进行双重标记判断,是因为setUserVisibleHint会多次回调,并且会在onCreateView执行前回调,必须确保onCreateView加载完毕且页面可见,才加载数据
        if (isViewCreated && isUIVisible && !isLoad) {
            isLoad = true;
            lazyLoadData();
        }
    }

    /**
     * 延迟加载
     * 子类必须重写此方法
     */
    protected abstract void  lazyLoadData();

    /**
     * 可见
     */
    protected void onVisible() {
        if(isViewCreated) {
            onVisibleAndCreated();
        }
        lazyLoad();
    }


    /**
     * 不可见
     */
    protected void onInvisible() {

    }

    /**
     * 可见
     */
    protected void onVisibleAndCreated() {

    }

    @Override
    public void onDestroyView() {
        isViewCreated = false;
        isUIVisible = false;
        isLoad = false;
        super.onDestroyView();
    }
}
